package com.yltrcc.blog.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yltrcc.blog.generate.domain.TodoMain;
import com.yltrcc.blog.generate.service.TodoMainService;
import com.yltrcc.blog.model.model.ApiResponse;
import com.yltrcc.blog.model.model.BaseApiResponse;
import com.yltrcc.blog.model.enums.TodoStatusEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 企业微信 群推送APi
 */
@RestController
@RequestMapping(value = "/api/todo")
public class TodoApiController {

    @Autowired
    private TodoMainService todoMainService;

    @RequestMapping(method = RequestMethod.POST, value = "/saveTodo")
    public BaseApiResponse saveTodo(@RequestBody TodoMain todoMain) {

        if (!StringUtils.hasText(todoMain.getContent())) {
            return new BaseApiResponse();
        }
        todoMain.setStatus(TodoStatusEnums.TODO.name());
        todoMain.setCreateTime(new Date());
        todoMain.setUpdateTime(new Date());

        todoMainService.save(todoMain);

        return new BaseApiResponse();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/updateTodo")
    public BaseApiResponse updateTodo(@RequestBody TodoMain todoMain) {

        if (!StringUtils.hasText(todoMain.getContent())) {
            return new BaseApiResponse();
        }
        if (todoMain.getId() == null) {
            return new BaseApiResponse();
        }
        todoMain.setUpdateTime(new Date());

        todoMainService.updateById(todoMain);

        return new BaseApiResponse();
    }

    /**
     * 显示所有小记
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getTodo")
    public ApiResponse<TodoMain> getTodo(@RequestParam(value = "page", defaultValue = "1") int page,
                                                 @RequestParam(value = "limit", defaultValue = "8") int limit,
                                                 @RequestParam(value = "status", defaultValue = "RUNNING") String status) {

        QueryWrapper<TodoMain> wrapper = new QueryWrapper<>();
        //update_time 降序  isAsc) 是否升序排列 true=asc，false=desc
        wrapper
                .orderBy(true, false, "update_time");
        //查询
        wrapper.eq("status", "RUNNING").or().eq("status", "TODO");
        Page<TodoMain> todoMainPage = todoMainService.page(new Page<>(page, limit), wrapper);

        return new ApiResponse<>(todoMainPage.getRecords());
    }

}
